from rest_framework import serializers
from django.contrib.auth.models import User
from crm.models import *


class CompanydeptSerializer(serializers.ModelSerializer):
    class Meta:
        model = Companydept        
        fields = ['id','levelOneDept','levelTwoDept']

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['username', 'email', 'password',"is_active"]  # 根据你的需求调整字段
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        # 本函数用于创建user对象
        user = User(
            username=validated_data['username'],
            email=validated_data['email'],
            is_active=validated_data['is_active'],
            )
        user.set_password(validated_data['password'])   # 使用set_password()函数对密码进行哈希加密
        user.save()
        return user
    
class EmployeeSerializer(serializers.ModelSerializer):
    # 嵌套序列化器，关联Companydept和User对象
    # 可在1张表单中同时提交Employee, User, Dept 模型数据 
    dept = CompanydeptSerializer()
    user = UserSerializer()
    class Meta: 
        model = Employee
        fields = ['id', 'name','gender','birthday','user','phone','email','dept','jobtitle','is_valid']
        extra_kwargs = {
            'user': {'required': True},
            'dept': {'required': False},  # 根据你的需求调整是否为必填
        }
        
    def create(self, validated_data):
        # 从验证后的数据中弹出user对象数据
        user_data = validated_data.pop('user')

        # 检查user对象在User模型中是否存在，如果不存在则创建
        user_obj,_ = User.objects.get_or_create(**user_data)        
        print(user_obj)
        dept_data = validated_data.pop('dept', None)
        dept_obj = None
        # 创建员工对象，并将用户对象和其他验证后的数据作为参数传入
        print(validated_data)
        employee = Employee.objects.create(user=user_obj,**validated_data)

        if dept_data:
            #如果部门数据存在，则检查 CompanyDept 模型中是否存在，如果存在，更新dept_obj
            try: 
                dept_obj = Companydept.objects.get(**dept_data)
                # 如果部门对象存在
                if dept_obj:
                    # 将部门对象赋值给员工的部门字段
                    employee.dept = dept_obj
                    # 保存员工对象
                    employee.save()
            except Companydept.DoesNotExist:
                # 如果部门对象不存在，则创建部门对象
                print("部门数据不存在")
                dept_obj = None
        return employee    
    
# Serializer for Account model
class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = ['id', 'name','cust_no','type' ,'industry', 'scale','country','province',
                  'city', 'post_code','address','finance_account','credit_quota','phone','email' ,'website']
        read_only_fields = ['id']


class AccountRelativeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = ['id', 'name','cust_no']
        read_only_fields = ['id']

class ContactListSerializer(serializers.ModelSerializer):
    # 这里可以包含额外的字段或方法，仅用于列表展示
    account = serializers.PrimaryKeyRelatedField(read_only=True)
    class Meta:
        model = Contact
        fields = ['id', 'name', 'gender', 'account', 'dept', 'title', 'phone', 'email', 'wechat', 'is_decisor', 'description']
        read_only_fields = ['id']

# Contact serializer for list, retrieve view
class ContactDetailSerializer(serializers.ModelSerializer):
    account = AccountRelativeSerializer()

    class Meta:
        model = Contact
        fields = ['id', 'name', 'gender', 'account', 'dept', 'title', 'phone', 'email', 'wechat', 'is_decisor', 'description']
        read_only_fields = ['id']

# Contact Serializer for create view
class ContactCreateSerializer(serializers.ModelSerializer):
    account = serializers.PrimaryKeyRelatedField(queryset=Account.objects.all())

    class Meta:
        model = Contact
        fields = ['id', 'name', 'gender', 'account', 'dept', 'title', 'phone', 'email', 'wechat', 'is_decisor', 'description']
        read_only_fields = ['id']

# Contact serializer for update view
class ContactUpdateSerializer(serializers.ModelSerializer):
    account = serializers.PrimaryKeyRelatedField(queryset=Account.objects.all(), required=False)
    class Meta:
        model = Contact
        fields = ['id', 'name', 'gender', 'account', 'dept', 'title', 'phone', 'email', 'wechat', 'is_decisor', 'description']
        read_only_fields = ['id']


# serializer for Productline model
class ProductLineSerializers(serializers.ModelSerializer):
    class Meta:
        model = ProductLine
        fields = ['id', 'name', 'description']
        read_only_fields = ['id']

# serializer for BizOpp model
class BizOppSerializer(serializers.ModelSerializer):
    account = AccountSerializer()
    contact = ContactListSerializer()
    owner = EmployeeSerializer()
    owner_dept = CompanydeptSerializer()

    class Meta:
        model = BizOpp
        fields = ['id','name','account','contact','value','lead_source','probability','owner','owner_dept','closed_expect','description','stage','closed_at']
        read_only_fields = ['id']

class BizOppListSerializer(serializers.ModelSerializer):
    account = serializers.PrimaryKeyRelatedField(read_only=True)
    contact = serializers.PrimaryKeyRelatedField(read_only=True)
    owner = serializers.PrimaryKeyRelatedField(read_only=True)
    owner_dept = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = BizOpp
        fields = ['id','name','account','contact','value','lead_source','probability','owner','owner_dept','closed_expect','description','stage','closed_at']
        read_only_fields = ['id']

class BizOppCreateSerializer(serializers.ModelSerializer):
    account = serializers.PrimaryKeyRelatedField(queryset=Account.objects.all())
    contact = serializers.PrimaryKeyRelatedField(queryset=Contact.objects.all())
    owner = serializers.PrimaryKeyRelatedField(queryset=Employee.objects.all())
    owner_dept = serializers.PrimaryKeyRelatedField(queryset=Companydept.objects.all())

    class Meta:
        model = BizOpp
        fields = ['id','name','account','contact','value','lead_source','probability','owner','owner_dept','closed_expect','description','stage','closed_at']
        read_only_fields = ['id']

class BizOppUpdateSerializer(serializers.ModelSerializer):
    account = serializers.PrimaryKeyRelatedField(queryset=Account.objects.all(),required=False)
    contact = serializers.PrimaryKeyRelatedField(queryset=Contact.objects.all(),required=False)
    owner = serializers.PrimaryKeyRelatedField(queryset=Employee.objects.all(),required=False)
    owner_dept = serializers.PrimaryKeyRelatedField(queryset=Companydept.objects.all())
    class Meta:
        model = BizOpp
        fields = ['id','name','account','contact','value','lead_source','probability','owner','owner_dept','closed_expect','description','stage','closed_at']
        read_only_fields = ['id']



# serializaer for Deal model 
class DealSerializer(serializers.ModelSerializer):
    account = AccountSerializer()
    opportunity = BizOppListSerializer()
    employee = EmployeeSerializer()

    class Meta:
        model = Deal
        fields = ['id', 'order_number', 'contract','title','date','total_amount','account','opportunity','employee']
        read_only_fields = ['id','order_number']


# serializaer for Communication model 
class CommunicationSerializer(serializers.ModelSerializer):
    account = AccountSerializer()
    contact = ContactListSerializer(many=True)
    employee = EmployeeSerializer()

    class Meta:
        model = Communication
        fields = ['id', 'description','communicate_date','outcome','account','contact','employee']
        read_only_fields = ['id']

